package org.jeecg.modules.lab.exam.paper.controller;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.exam.entity.*;
import org.jeecg.modules.lab.exam.exam.service.ILabExamService;
import org.jeecg.modules.lab.exam.paper.service.ILabExamPaperQuestionAnswerService;
import org.jeecg.modules.lab.exam.paper.service.ILabExamPaperQuestionService;
import org.jeecg.modules.lab.exam.paper.service.ILabExamPaperService;
import org.jeecg.modules.lab.exam.paper.vo.LabExamPaperPage;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.exam.paper.vo.LabExamPaperQuestionPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


/**
 * @Description: 考试记录
 * @Author: jeecg-boot
 * @Date: 2023-08-30
 * @Version: V1.0
 */
@Api(tags = "考试记录")
@RestController
@RequestMapping("/exam/paper/labExamPaper")
@Slf4j
public class LabExamPaperController {
    @Autowired
    private ILabExamPaperService labExamPaperService;
    @Autowired
    private ILabExamPaperQuestionService labExamPaperQuestionService;
    @Autowired
    private ILabExamPaperQuestionAnswerService labExamPaperQuestionAnswerService;
    @Autowired
    private ILabExamService labExamService;

    @Autowired
    private ILabCronJobService labCronJobService;

    /**
     * 分页列表查询
     *
     * @param labExamPaper
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "考试记录-分页列表查询")
    @ApiOperation(value = "考试记录-分页列表查询", notes = "考试记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabExamPaper>> queryPageList(LabExamPaper labExamPaper,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<LabExamPaper> queryWrapper = QueryGenerator.initQueryWrapper(labExamPaper, req.getParameterMap());
        Page<LabExamPaper> page = new Page<LabExamPaper>(pageNo, pageSize);
        IPage<LabExamPaper> pageList = labExamPaperService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "考试记录-批量删除")
    @ApiOperation(value = "考试记录-批量删除", notes = "考试记录-批量删除")
//    @RequiresPermissions("paper:lab_exam_paper:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labExamPaperService.delBatchMain(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            List<LabCronJob> jobs = new ArrayList<>();
            for (int i = 0; i < idList.length; i++) {
                String condition1 = "paper_id='" + idList[i] + "'";
                String condition2 = "id='" + idList[i] + "'";
                jobs.add(new LabCronJob("lab_exam_paper_question", "2", condition1, time));
                jobs.add(new LabCronJob("lab_exam_paper_question_answer", "2", condition1, time));
                jobs.add(new LabCronJob("lab_exam_paper", "2", condition2, time));
            }
            for (int i = 0; i < jobs.size(); i++) {
                jobs.get(i).setOrderNum(i + 1);
            }
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "考试记录-通过id查询")
    @ApiOperation(value = "考试记录-通过id查询", notes = "考试记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabExamPaper> queryById(@RequestParam(name = "id", required = true) String id) {
        LabExamPaper labExamPaper = labExamPaperService.getById(id);
        if (labExamPaper == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labExamPaper);

    }

    /**
     * @param examId
     * @return
     */
    @ApiOperation(value = "考试记录-通过考试id和用户id查询", notes = "考试记录-通过考试id和用户id查询")
    @GetMapping(value = "/queryByEIdAndUId")
    public Result<LabExamPaper> queryByEIdAndUId(@RequestParam(name = "examId", required = true) String examId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<LabExamPaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_id", examId);
        queryWrapper.eq("user_id", sysUser.getId());
        LabExamPaper labExamPaper = labExamPaperService.getOne(queryWrapper);
//		 if(labExamPaper==null) {
//			 return Result.error("未找到对应数据");
//		 }
        return Result.OK(labExamPaper);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "考试记录考题表通过主表ID查询")
    @ApiOperation(value = "考试记录考题表主表ID查询", notes = "考试记录考题表-通主表ID查询")
    @GetMapping(value = "/queryLabExamPaperQuestionByMainId")
    public Result<List<LabExamPaperQuestion>> queryLabExamPaperQuestionListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabExamPaperQuestion> labExamPaperQuestionList = labExamPaperQuestionService.selectByMainId(id);
        return Result.OK(labExamPaperQuestionList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "考试记录答案通过主表ID查询")
    @ApiOperation(value = "考试记录答案主表ID查询", notes = "考试记录答案-通主表ID查询")
    @GetMapping(value = "/queryLabExamPaperQuestionAnswerByMainId")
    public Result<List<LabExamPaperQuestionAnswer>> queryLabExamPaperQuestionAnswerListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabExamPaperQuestionAnswer> labExamPaperQuestionAnswerList = labExamPaperQuestionAnswerService.selectByMainId(id);
        return Result.OK(labExamPaperQuestionAnswerList);
    }


    /**
     * 更新试题答案
     *
     * @return
     */
    @ApiOperation(value = "更新试题答案", notes = "考试记录答案-更新试题答案")
    @DeleteMapping(value = "/updateQuAnswere")
    public void updateQuAnswere(@RequestParam(name = "paperId", required = true) String paperId,
                                @RequestParam(name = "quId", required = true) String quId,
                                @RequestParam(name = "answer", required = true) String answer) {
        labExamPaperQuestionService.updateQuAnswere(paperId, quId, answer);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_exam_paper_question", "1", time, 1));
            jobs.add(new LabCronJob("lab_exam_paper_question_answer", "1", time,2));
            labCronJobService.saveBatch(jobs);
        }
    }


    /**
     * 提交考试试卷
     *
     * @return
     */
    @ApiOperation(value = "提交考试试卷", notes = "考试记录-提交考试试卷")
    @DeleteMapping(value = "/submitPaper")
    public Result<String> submitPaper(@RequestParam(name = "paperId", required = true) String paperId,
                                      @RequestParam(name = "quId", required = true) String quId,
                                      @RequestParam(name = "answer", required = true) String answer) {
        labExamPaperQuestionService.updateQuAnswere(paperId, quId, answer);
        Double score = labExamPaperService.submitPaper(paperId);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_exam_paper_question", "1", time, 1));
            jobs.add(new LabCronJob("lab_exam_paper_question_answer", "1", time,2));
            jobs.add(new LabCronJob("lab_exam_paper", "1", time,3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK(score.toString());
    }


    /**
     * 创建试卷
     *
     * @param examId
     * @return
     */
    @ApiOperation(value = "考试记录-创建试卷", notes = "考试记录-创建试卷")
    @GetMapping(value = "/createPaper")
    public Result<LabExamPaperPage> createPaper(@RequestParam(name = "examId", required = true) String examId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LabExamPaperPage labExamPaperPage = new LabExamPaperPage();
        QueryWrapper<LabExamPaper> pWrapper = new QueryWrapper<>();
        pWrapper.eq("exam_Id", examId);
        pWrapper.eq("user_Id", sysUser.getId());
        LabExamPaper labExamPaper = labExamPaperService.getOne(pWrapper);
        if (labExamPaper == null) {
            //创建试卷
            LabExam labExam = labExamService.getById(examId);
            String paperId = this.labExamPaperService.creatPaper(sysUser, labExam);
            //查询考试试卷
            labExamPaperPage = queryPaper(paperId);
            return Result.OK(labExamPaperPage);
        } else {
            if (labExamPaper.getState().equals("考试中")) {
                //查询考试试卷
                labExamPaperPage = queryPaper(labExamPaper.getId());
                return Result.OK(labExamPaperPage);
            } else {
                return Result.OK("考试已结束!");
            }
        }
    }

    /**
     * 查询试卷结果
     *
     * @param paperId
     * @return
     */
    @ApiOperation(value = "考试记录-查询试卷结果", notes = "考试记录-查询试卷结果")
    @GetMapping(value = "/queryExamResult")
    public Result<LabExamPaperPage> queryExamResult(@RequestParam(name = "paperId", required = true) String paperId) {
        LabExamPaperPage labExamPaperPage = queryPaper(paperId);
        return Result.OK(labExamPaperPage);
    }


    /**
     * 查询考试试题
     *
     * @param paperId
     * @return
     */
    public LabExamPaperPage queryPaper(String paperId) {
        LabExamPaperPage labExamPaperPage = new LabExamPaperPage();
        LabExamPaper labExamPaper = labExamPaperService.getById(paperId);
        BeanUtils.copyProperties(labExamPaper, labExamPaperPage);
        labExamPaperPage.setRadioList(getPaperQuestionPage(labExamPaper.getId(), "单选题"));
        labExamPaperPage.setMultiList(getPaperQuestionPage(labExamPaper.getId(), "多选题"));
        labExamPaperPage.setJudgeList(getPaperQuestionPage(labExamPaper.getId(), "判断题"));
        return labExamPaperPage;
    }

    /**
     * 获取考试题
     *
     * @param paperId
     * @param qType
     * @return
     */
    public List<LabExamPaperQuestionPage> getPaperQuestionPage(String paperId, String qType) {
        QueryWrapper<LabExamPaperQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("paper_Id", paperId);
        queryWrapper.eq("question_type", qType);
        queryWrapper.orderByAsc("sort");
        //试题
        List<LabExamPaperQuestion> labExamPaperQuestions = labExamPaperQuestionService.list(queryWrapper);

        List<LabExamPaperQuestionPage> labExamPaperQuestionPageList = new ArrayList<>();
        //试题的答案
        for (int i = 0; i < labExamPaperQuestions.size(); i++) {
            LabExamPaperQuestionPage labExamPaperQuestionPage = new LabExamPaperQuestionPage();
            BeanUtils.copyProperties(labExamPaperQuestions.get(i), labExamPaperQuestionPage);

            QueryWrapper<LabExamPaperQuestionAnswer> wrapper = new QueryWrapper<>();
            String questionId = labExamPaperQuestions.get(i).getQuestionId();
            wrapper.clear();
            wrapper.eq("paper_Id", paperId);
            wrapper.eq("question_Id", questionId);
            wrapper.orderByAsc("sort");
            List<LabExamPaperQuestionAnswer> labExamPaperQuestionAnswerList = labExamPaperQuestionAnswerService.list(wrapper);
            labExamPaperQuestionPage.setAnswerList(labExamPaperQuestionAnswerList);

            labExamPaperQuestionPageList.add(labExamPaperQuestionPage);
        }
        return labExamPaperQuestionPageList;
    }


}
